//
//  DetailListJumpHelp.m
//  翼安保
//
//  Created by duzhi on 2024/4/28.
//

#import "DetailListJumpHelp.h"
#import "DetailListViewController.h"
#import "ScanViewController.h"
#import "LBXPermission.h"
#import <CoreNFC/CoreNFC.h>
#import "HomeApi.h"

@interface DetailListJumpHelp()<NFCNDEFReaderSessionDelegate>
@property (assign, nonatomic) int detailListType;
@property (nonatomic, strong) NFCTagReaderSession *session;
@property (nonatomic, strong) UIViewController *vc;

@property (nonatomic, strong) NFCNDEFReaderSession *readerSession;
@end

@implementation DetailListJumpHelp

- (instancetype)init {
    if (self = [super init]) {
        self.detailListType = 0;
    };
    return self;
}

- (void)inputSearch:(UIViewController *)vc type:(int)type {
    self.detailListType = type;
    self.vc = vc;
    UIAlertController *alertview = [UIAlertController alertControllerWithTitle:@"请输入用品标识码" message:nil preferredStyle:UIAlertControllerStyleAlert];
    alertview.overrideUserInterfaceStyle = UIUserInterfaceStyleUnspecified;
    UIAlertAction *left = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil];
    UIAlertAction *right = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        NSLog(@"%@",alertview.textFields.firstObject.text);
        NSString *code = alertview.textFields.firstObject.text;
        if (code.length >0) {
            [self getInfoByCode:alertview.textFields.firstObject.text];
        }
    }];
    [left setValue:UIColorFromRGB(0x1196db) forKey:@"titleTextColor"];
    [right setValue:UIColorFromRGB(0x1196db) forKey:@"titleTextColor"];
    [alertview addAction:left];
    [alertview addAction:right];
    [alertview addTextFieldWithConfigurationHandler:nil];
    [vc presentViewController:alertview animated:YES completion:nil];
}

- (void)scanSearch:(UIViewController *)vc type:(int)type {
    self.detailListType = type;
    self.vc = vc;
    [LBXPermission authorizeWithType:LBXPermissionType_Camera completion:^(BOOL granted, BOOL firstTime) {
        if (granted) {
            ScanViewController *scan = [ScanViewController new];
            Weak(wself, self)
            scan.scanViewControllerFinishBlock = ^(NSString *resultStr) {
                [wself getInfoByCode:resultStr];
            };
            [vc.navigationController pushViewController:scan animated:NO];
        }
        else if(!firstTime)
        {
            [LBXPermissionSetting showAlertToDislayPrivacySettingWithTitle:@"提示" msg:@"没有相机权限，是否前往设置" cancel:@"取消" setting:@"设置" ];
        }
    }];
}

- (void)NFCSearch:(UIViewController *)vc type:(int)type {
    self.vc = vc;
    self.detailListType = type;
//    if (@available(iOS 13.0, *)) {
//        // 初始化 NFC 设置代理 NFCTagReaderSessionDelegate
//        self.session = [[NFCTagReaderSession alloc]
//                    initWithPollingOption:(NFCPollingISO14443 | NFCPollingISO15693 | NFCPollingISO15693) delegate:self queue:dispatch_get_main_queue()];
//        // NFC 显示提示信息
//        self.session.alertMessage = @"准备扫描，请将卡片贴近手机";
//        // 开启 NFC
//        [self.session beginSession];
//
//    }
    self.readerSession = [[NFCNDEFReaderSession alloc] initWithDelegate:self queue:dispatch_get_main_queue() invalidateAfterFirstRead:true];
    self.readerSession.alertMessage = @"准备扫描，请将卡片贴近手机";
    [self.readerSession beginSession];
}

#pragma mark -NFCNDEFReaderSessionDelegate
- (void)readerSessionDidBecomeActive:(NFCNDEFReaderSession *)session {
    NSLog(@"readerSessionDidBecomeActive");
}


- (void)readerSession:(NFCNDEFReaderSession *)session didInvalidateWithError:(NSError *)error {
    NSLog(@"readerSession:didInvalidateWithError: (%@)", [error localizedDescription]);
}

- (void)readerSession:(NFCNDEFReaderSession *)session didDetectTags:(NSArray<__kindof id<NFCNDEFTag>> *)tags {
    NSLog(@"readerSession:(NFCNDEFReaderSession *)session didDetectTags: %@", tags);
    [tags.firstObject readNDEFWithCompletionHandler:^(NFCNDEFMessage * _Nullable message, NSError * _Nullable) {
        [self readNfcValue:message];
        [session invalidateSession];
    }];
}

- (void)readerSession:(NFCNDEFReaderSession *)session didDetectNDEFs:(NSArray<NFCNDEFMessage *> *)messages {
    NSLog(@"readerSession:(NFCNDEFReaderSession *)session didDetectNDEFs: %@", messages);
    [session invalidateSession];
    [self readNfcValue:messages.firstObject];
}

- (void)readNfcValue:(NFCNDEFMessage * _Nullable )message {
    NSMutableArray *datas = [NSMutableArray new];
    for (NFCNDEFPayload *record in message.records) {
        NSData *payload = record.payload;
        NSString *payloadString = [[NSString alloc] initWithData:payload encoding:NSUTF8StringEncoding];
        //去除前缀
        payloadString = extractDigitsFromNSString(payloadString);
        NSLog(@"检测到NDEF消息: %@", payloadString);
        if (payloadString.length > 0) {
            [datas addObject:payloadString];
        }
    }
    if (datas.count == 0) {
        [MBProgressHUD showTextHUD:@"未识别出NFC格式"];
        return;
    }
    //@"01001150172001361"
    //[self getInfoByCode:@"01001150172001361"];
    [self getInfoByCode:datas.firstObject];
    
//    UIAlertController *alertview = [UIAlertController alertControllerWithTitle:@"请选择任一标识码：" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
//
//    for (NSString *message in datas) {
//        UIAlertAction *idAction = [UIAlertAction actionWithTitle:[NSString stringWithFormat:@"标识码:%@",message] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action){
//            [self getInfoByCode:message];
//        }];
//        [alertview addAction:idAction];
//    }
    //测试用:
//    UIAlertAction *testAction1 = [UIAlertAction actionWithTitle:[NSString stringWithFormat:@"测试标识码1:%@",@"01001150172001361"] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action){
//        [self getInfoByCode:@"01001150172001361"];
//    }];
//    [alertview addAction:testAction1];
//    //测试用:
//    UIAlertAction *testAction2 = [UIAlertAction actionWithTitle:[NSString stringWithFormat:@"测试标识码2:%@",@"01001150117001082"] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action){
//        [self getInfoByCode:@"01001150117001082"];
//    }];
//    [alertview addAction:testAction2];
//    //测试用:
//    UIAlertAction *testAction3 = [UIAlertAction actionWithTitle:[NSString stringWithFormat:@"测试标识码3:%@",@"01001150117001717"] style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action){
//        [self getInfoByCode:@"01001150117001717"];
//    }];
//    [alertview addAction:testAction3];
    
    
//    UIAlertAction *cance = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
//    [alertview addAction:cance];
//    [self.vc presentViewController:alertview animated:YES completion:nil];
}

NSString *extractDigitsFromNSString(NSString *inputString) {
    NSError *error;
    NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"\\d+" options:0 error:&error];
    if (!regex || error) {
        NSLog(@"Error creating regular expression: %@", error.localizedDescription);
        return @"";
    }

    NSArray<NSTextCheckingResult *> *matches = [regex matchesInString:inputString options:0 range:NSMakeRange(0, inputString.length)];
    NSMutableString *digits = [NSMutableString string];
    for (NSTextCheckingResult *match in matches) {
        [digits appendString:[inputString substringWithRange:match.range]];
    }
    return digits;
}

//- (void)tagReaderSession:(NFCTagReaderSession *)session didDetectTags:(NSArray<__kindof id<NFCTag>> *)tags API_AVAILABLE(ios(13.0)) API_UNAVAILABLE(watchos, macos, tvos) {
//    NSMutableArray *strs = [NSMutableArray new];
//    for (id<NFCTag> currentTag in tags) {
//        NSData *data ;
//        if (currentTag.type == NFCTagTypeMiFare) {
//            id<NFCMiFareTag> mifareTag = [currentTag asNFCMiFareTag];
//            data = mifareTag.identifier;
//            [session connectToTag:mifareTag completionHandler:^(NSError * _Nullable error) {
//                        NSLog(@"连接失败:%@",error);
//                        [mifareTag readNDEFWithCompletionHandler:^(NFCNDEFMessage * message, NSError * error) {
//                            NSLog(@"读卡失败:%@",error);
//                            for (NFCNDEFPayload *record in message.records) {
//                                NSData *payload = record.payload;
//                                NSString *payloadString = [[NSString alloc] initWithData:payload encoding:NSUTF8StringEncoding];
//                                NSLog(@"检测到NDEF消息: %@", payloadString);
//                            }
//                        }];
//            }];
//        }else if (currentTag.type == NFCTagTypeISO15693){
//            id<NFCISO15693Tag> mifareTag = [currentTag asNFCISO15693Tag];
//            data = mifareTag.identifier;
//        }else if (currentTag.type == NFCTagTypeISO7816Compatible){
//            id<NFCISO7816Tag> mifareTag = [currentTag asNFCISO7816Tag];
//            data = mifareTag.identifier;
//        }
//        NSString *str = [self convertDataBytesToHex:data];
//        NSLog(@"tagReaderSession didDetectTags str:%@", str);
//        [strs addObject:str];
//    }
//    if (strs.count == 0) {
//        [MBProgressHUD showTextHUD:@"未识别出NFC格式"];
//    }else{
//        NSLog(@"识别结果:%@", strs);
//    }
//    
//}
//
//- (NSString *)convertDataBytesToHex:(NSData *)dataBytes {
//    if (!dataBytes || [dataBytes length] == 0) {
//        return @"";
//    }
//    NSMutableString *hexStr = [[NSMutableString alloc] initWithCapacity:[dataBytes length]];
//    [dataBytes enumerateByteRangesUsingBlock:^(const void *bytes, NSRange byteRange, BOOL *stop) {
//        unsigned char *dataBytes = (unsigned char *)bytes;
//        for (NSInteger i = 0; i < byteRange.length; i ++) {
//            NSString *singleHexStr = [NSString stringWithFormat:@"%x", (dataBytes[i]) & 0xff];
//            if ([singleHexStr length] == 2) {
//                [hexStr appendString:singleHexStr];
//            } else {
//                [hexStr appendFormat:@"0%@", singleHexStr];
//            }
//        }
//    }];
//    return hexStr;
//}

- (void)getInfoByCode:(NSString *)code{
    if (!code||code.length == 0) {
        return;
    }
    //code = @"05016160037000018";
    NSMutableDictionary *dic = [NSMutableDictionary new];
    dic[@"code"] = code;
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.vc.navigationController.view animated:YES];
    [[AFNNetWorkManager shareAFNNetWorkManager] Get:getInfoByCodeUrl parameters:dic success:^(NSURLSessionDataTask *task, Result *result) {
        NSLog(@"请求地址：%@\n请求参数：%@\n请求数据：%@",task.currentRequest.URL.absoluteString,dic,result.data);
        [hud hideAnimated:YES];
        if (result.code == 200) {
            NSMutableArray *datas = [DetailListModel mj_objectArrayWithKeyValuesArray:result.data];
            if (!datas||datas.count==0) {
                [MBProgressHUD showTextHUD:@"暂无数据"];
                return;
            }
            DetailListViewController *vc = [DetailListViewController new];
            vc.type = self.detailListType;
            vc.datas = datas;
            if (self.detailListType == 3) {
                if (self.replacedModel) {
                    vc.replacedModel = self.replacedModel;
                }
                DetailListViewController *fromVC = (DetailListViewController*)self.vc;
                Weak(wself, self)
                Weak(wfromVc, fromVC)
                vc.detailListFinishReplaceBlock = ^(DetailListModel * _Nonnull replacedModel, DetailListModel * _Nonnull newModel) {
                    //刷新mygoods
                    [wself getMyFoodsFinish:^(NSMutableArray *datas) {
                        wfromVc.datas = datas;
                    } from:wfromVc];
                };
            }
            [self.vc.navigationController pushViewController:vc animated:NO];
        }else {
            [MBProgressHUD showTextHUD:result.msg];
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        [hud hideAnimated:YES];
        [MBProgressHUD showTextHUD:@"请检查网络设置"];
    }];
}

- (void)getMyFoods:(UIViewController *)fromVc {
    [self getMyFoodsFinish:^(NSMutableArray *datas) {
        DetailListViewController *vc = [DetailListViewController new];
        vc.type = 1;
        vc.datas = datas;
        [fromVc.navigationController pushViewController:vc animated:NO];
    } from:fromVc];
}

- (void)getMyFoodsFinish:(void(^)(NSMutableArray *datas))finishBlock from:(UIViewController *)fromVc{
    [[NSNotificationCenter defaultCenter] postNotificationName:NotifcationName_foodExpairChange object:nil];
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:fromVc.navigationController.view animated:YES];
    [[AFNNetWorkManager shareAFNNetWorkManager] Get:getMyFoodsUrl parameters:nil success:^(NSURLSessionDataTask *task, Result *result) {
        [hud hideAnimated:YES];
        if (result.code == 200) {
            NSMutableArray *datas = [DetailListModel mj_objectArrayWithKeyValuesArray:result.data];
            if (!datas||datas.count==0) {
                [MBProgressHUD showTextHUD:@"暂无数据"];
                return;
            }
            if (finishBlock) {
                finishBlock(datas);
            }
        }else {
            [MBProgressHUD showTextHUD:result.msg];
        }
    } failure:^(NSURLSessionDataTask *task, NSError *error) {
        [hud hideAnimated:YES];
        [MBProgressHUD showTextHUD:@"请检查网络设置"];
    }];
}

@end
